package com.dly.blog.controller;

import com.dly.blog.msg.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;

import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/11 13:25
 */
public class BaseController {

    public <T> ResponseEntity<T> operate(Supplier<T> sp){
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(sp.get());
    }

    public <T> ResponseEntity<T> operate(Supplier<T> sp, BindingResult br){
        validateFiled(br);
       return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(sp.get());
    }

    public  <T> R<T> success(){
        return R.ok();
    }

    public <T> R<T> successDate(T data){
        return R.ok(data);
    }

    public void validateFiled(BindingResult br){

        if(br.hasErrors()){
            throw new IllegalArgumentException(br
                    .getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .distinct()
                    .toList()
                    .toString()
            );
        }

    }
}
